#!/usr/bin/perl
# 2013/05/24 Make graph of distance vs association frequnecy

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [map file] -o [output file]\n";
}

my %opt;
getopts("i:o:", \%opt);
my $FILE_map = $opt{i};
my $FILE_out = $opt{o};

my $Resolution = 100;

#---------------------------------------
# collect information
#---------------------------------------
my %data;
my $fh_map = IO::File->new($FILE_map) or die "cannot open $FILE_map: $!";
while($_ = $fh_map->getline()){
	s/\r?\n//;
	my ($id, $chr1, $loc1, $direction1, $mapQ1, $hinID1, $hinLoc1, $chr2, $loc2, $direction2, $mapQ2, $hinID2, $hinLoc2, $type, $num, $locations) = split /\t/;

	if($chr1 ne $chr2){
		next;
	}

	if($type ne 'U:U'){
		next;
	}


	my $combination = 'NA';
	if(($direction1 eq '+') and ($direction2 eq '+')){
		if($loc1 < $loc2){
			$combination = 'in-in';
		}else{
			$combination = 'out-out';
		}
	}elsif(($direction1 eq '-') and ($direction2 eq '-')){
		if($loc1 < $loc2){
			$combination = 'out-out';
		}else{
			$combination = 'in-in';
		}
	}elsif(($direction1 eq '+') and ($direction2 eq '-')){
		$combination = 'right-right';
	}elsif(($direction1 eq '-') and ($direction2 eq '+')){
		$combination = 'left-left';
	}

	my $distance= abs($loc1 - $loc2);
	my $category = int($distance / $Resolution) * $Resolution;

	$data{$category}{$combination}++;
}
$fh_map->close();


#---------------------------------------
# output distance vs freqeuncy
#---------------------------------------
my $fh_out = IO::File->new($FILE_out, 'w') or die "cannot write $FILE_out: $!";
$fh_out->print("distance\tin-in\tout-out\tright-right\tleft-left\n");
foreach my $distance(sort{$a <=> $b} keys %data){
	$fh_out->print("$distance");
	foreach my $combination(qw(in-in out-out right-right left-left)){
		my $num = 0;
		if(exists $data{$distance}{$combination}){
			$num = $data{$distance}{$combination};
		}
		$fh_out->print("\t$num");
	}
	$fh_out->print("\n");
}
$fh_out->close();

